<?php

/**
 * Created by PhpStorm.
 * User: aa
 * Date: 15/10/21
 * Time: 下午3:37
 */
include_once "Mysql.php";

class FoodServer {

	public function getAllCategory() {
		$db = new Mysql('127.0.0.1', 'root', '', 'jl', '');
		$sql = "select  * FROM jl_food_category";
		$query = $db->query($sql);
		$list = array();
		while ($result = $db->fetch_array($query)) {
			$list[] = array(
				'id' => $result['id'],
				'title' => $result['title'],
				'kind' => $result['kind'],
			);
		}
		return $list;

	}

	public function getInfoByTitle($title) {
		$db = new Mysql('127.0.0.1', 'root', '', 'jl', '');
		$sql = "SELECT * FROM jl_food_category_subclass where title='" . $title . "'";
		$query = $db->query($sql);
		$result = $db->fetch_array($query);
		return $result;
	}

	public function getFoodsInfoByName($name) {
		$db = new Mysql('127.0.0.1', 'root', '', 'jl', '');
		$sql = "SELECT * FROM jl_foods where name='" . $name . "'";
		$query = $db->query($sql);
		$result = $db->fetch_array($query);
		return $result;
	}

	public function addFoods($keyString, $valueString) {
		$db = new Mysql('127.0.0.1', 'root', '', 'jl', '');
		return $db->insert('jl_foods', $keyString, $valueString);
	}

	public function addFoodsUnitsInfo($keyString, $valueString) {
		$db = new Mysql('127.0.0.1', 'root', '', 'jl', '');
		return $db->insert('jl_foods_units', $keyString, $valueString);
	}

	public function isExistRelation($foodId, $categoryId, $catagorySubId = 0) {
		$db = new Mysql('127.0.0.1', 'root', '', 'jl', '');
		$sql = "SELECT * FROM jl_food_relation_category where food_id=" . $foodId . " and category_id=" . $categoryId;
		if (empty($categoryId)) {
			$sql .= " and catagory_sub_id=" . $catagorySubId;
		}
		$query = $db->query($sql);
		$result = $db->fetch_array($query);
		return $result;
	}

	public function addRelation($keyString, $valueString) {
		$db = new Mysql('127.0.0.1', 'root', '', 'jl', '');
		return $db->insert('jl_food_relation_category', $keyString, $valueString);
	}

	public function modifyRelation($foodId, $categoryId, $subCategoryId) {
		$db = new Mysql('127.0.0.1', 'root', '', 'jl', '');
		$sql = "UPDATE jl_food_relation_category SET catagory_sub_id=" . $subCategoryId . " WHERE food_id=" . $foodId . " and category_id=" . $categoryId;
		return $db->query($sql);
	}

	public function getAllFoods($id1, $id2) {
		$db = new Mysql('127.0.0.1', 'root', '', 'jl', '');
		$sql = "SELECT id,name FROM jl_foods WHERE id>=" . $id1 . " and  id <" . $id2;
		$query = $db->query($sql);
		$list = array();
		while ($result = $db->fetch_array($query)) {
			$list[] = array(
				'id' => $result['id'],
				'name' => $result['name'],
			);
		}
		return $list;
	}
}